#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/06/08 16:49
# @Author  : elegantfrog
# @FileName: svr.py

'''
生成依赖文件：pipreqs . --encoding=utf-8 --force
依赖安装：pip install -r requirements.txt
'''

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_request_id import RequestID
from utils.logs import Logging
from utils.utils import aUtils
from utils.config import config
from utils.client import aMqtt
import time
from redis import Redis, ConnectionPool
import json
import base64
import os

# from routes.user import user
# from routes.admin import admin
# from routes.seedlight import seedlight


Mqtt = aMqtt()

app = Flask(__name__)

CORS(app, supports_credentials=True, resources={r'/*': {'origins': '*'}})

app.app_context().push()
req = RequestID(app).id
utils = aUtils(req)
logging = Logging(__name__)
db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:hhuc1115@ai.seedlight.cn:31406/seed2022'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False


def connect_redis():
    try:
        redis_pool = ConnectionPool(host=config['redis']['host'], port=config['redis']['port'],
                                    password=config['redis']['password'], db=config['redis']['db'],
                                    max_connections=config['redis']['max_connections'], decode_responses=True
                                    )
        redisCli = Redis(connection_pool=redis_pool)
        return redisCli
    except Exception as e:
        print(e)


@app.route('/seedlight/login', methods=['POST'])
def login():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = msg['route'].split('/')[-1]
        sql_query = aUtils.getSqlText('user/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getUserList', methods=['POST'])
def getUserList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('user/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/operateUser', methods=['POST'])
def operateUser():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('user/' + code, {})
        for sql in sql_query.split(';'):
            db.session.execute(sql, params['json'])
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/operatePwd', methods=['POST'])
def operatePwd():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('user/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            print(result)
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getNewImage', methods=['POST'])
def getNewImage():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        data = {
            'deviceId': params['json']['deviceId'],
            'payload': {"method": "d5"}
        }
        Mqtt.on_publish(data)
        logging.info(msg)
        return utils.resData(1, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getImageList', methods=['POST'])
def getImageList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = msg['route'].split('/')[-1]
        ret = []
        methos = 'POST'
        url = 'http://ai.seedlight.cn:31341/rest/sql/seed2022'
        header = {'Authorization': 'Basic cm9vdDp0YW9zZGF0YQ=='}
        sql = "select * from d_img where devicdid='{deviceId}' order by ts desc limit {start},{end}".format(
            deviceId=params['json']['deviceId'], start=params['json']['start'], end=params['json']['end'])
        resData = json.loads(utils.reqSvr(methos, url, header, sql))
        sqlTotal = "select * from d_img where devicdid='{deviceId}'".format(deviceId=params['json']['deviceId'])
        totalData = json.loads(utils.reqSvr(methos, url, header, sqlTotal))
        headList = resData['head']
        datas = resData['data']
        for item in datas:
            result = dict(zip(headList, item))
            ret.append(result)
        ret.append({'total': totalData['rows']})
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getRoleListByRoleId', methods=['POST'])
def getRoleListByRoleId():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('user/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getDeviceList', methods=['POST'])
def getDeviceList():
    try:
        params = utils.getReqParams(request)
        print(params)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('device/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        devList = ret[:-1]
        redisCli = connect_redis()
        for dev in devList:
            res = redisCli.hget(dev['deviceId'], 'realdata')
            status = redisCli.hget(dev['deviceId'], 'status')
            images = redisCli.hget(dev['deviceId'], 'images')
            if res and status and images:
                realdata = json.loads(res)
                dev['volt'] = realdata['volt']
                dev['cur'] = realdata['cur']
                dev['light'] = realdata['light']
                dev['temp'] = realdata['temp']
                dev['brightness'] = realdata['brightness']
                dev['status'] = status
                dev['imageUrl'] = json.loads(images)['imageUrl']
        redisCli.connection_pool.disconnect()
        devList.append(ret[-1])
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getRouteList', methods=['POST'])
def getRouteList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('device/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/batchAddDevice', methods=['POST'])
def batchAddDevice():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        sql_query = aUtils.getSqlText('device/addDevice', {})
        devList = params['json']['devList']
        if len(devList) > 0:
            for dev in devList:
                db.session.execute(sql_query, dev)
                db.session.commit()
            res = utils.resData(1, 'OK')
            msg['res'] = res
            logging.info(msg)
            return res
        else:
            utils.resData('数据列表为空，请重新上传！', 'ERROR')
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/operateDevice', methods=['POST'])
def operateDevice():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('device/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            print(result)
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getBarnList', methods=['POST'])
def getBarnList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('device/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        return {
            "errorMessage": e,
            "requestId": req.replace('', ''),
            "state": 'ERROR'
        }


@app.route('/seedlight/getTypeList', methods=['POST'])
def getTypeList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('barn/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        return {
            "errorMessage": e,
            "requestId": req.replace('', ''),
            "state": 'ERROR'
        }


@app.route('/seedlight/operateBarn', methods=['POST'])
def operateBarn():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('barn/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            print(result)
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/addGrain', methods=['POST'])
def addGrain():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('grain/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        print(e)
        return {
            "errorMessage": e,
            "requestId": req.replace('', ''),
            "state": 'ERROR'
        }


@app.route('/seedlight/updateGrain', methods=['POST'])
def updateGrain():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('grain/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        print(e)
        return {
            "errorMessage": e,
            "requestId": req.replace('', ''),
            "state": 'ERROR'
        }


@app.route('/seedlight/getGrainList', methods=['POST'])
def getGrainList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('grain/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        return {
            "errorMessage": e,
            "requestId": req.replace('', ''),
            "state": 'ERROR'
        }


@app.route('/seedlight/getOrganizationList', methods=['POST'])
def getOriganizationList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('grain/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        print(e)
        return {
            "errorMessage": e,
            "requestId": req.replace('', ''),
            "state": 'ERROR'
        }


@app.route('/seedlight/setBrightVal', methods=['POST'])
def setBrightVal():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        data = {
            'deviceId': params['json']['deviceId'],
            'payload': {"method": "d3", "params": {'value': params['json']['brightness']}}
        }
        Mqtt.on_publish(data)
        logging.info(msg)
        return utils.resData(1, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/setLightStatus', methods=['POST'])
def setLightStatus():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        data = {
            'deviceId': params['json']['deviceId'],
            'payload': {"method": "d6", "params": {'value': params['json']['light']}}
        }
        Mqtt.on_publish(data)
        logging.info(msg)
        return utils.resData(1, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getRealData', methods=['POST'])
def getRealData():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        data = {
            'deviceId': params['json']['deviceId'],
            'payload':
                {
                    "method": "d2",
                }
        }
        Mqtt.on_publish(data)
        time.sleep(2)
        ret = [{}]
        redisCli = connect_redis()
        status = redisCli.hget(params['json']['deviceId'], 'status')
        newImage = redisCli.hget(params['json']['deviceId'], 'images')
        realdataStr = redisCli.hget(params['json']['deviceId'], 'realdata')
        if realdataStr and status and newImage:
            realdata = json.loads(realdataStr)
            ret[0]['volt'] = realdata['volt']
            ret[0]['cur'] = realdata['cur']
            ret[0]['curThrd'] = realdata['curThrd']
            ret[0]['light'] = realdata['light']
            ret[0]['temp'] = realdata['temp']
            ret[0]['brightness'] = realdata['brightness']
            ret[0]['status'] = status
            ret[0]['imageUrl'] = json.loads(newImage)['imageUrl']
        else:
            ret[0]['volt'] = 0
            ret[0]['cur'] = 0
            ret[0]['curThrd'] = 0
            ret[0]['light'] = 0
            ret[0]['temp'] = 0
            ret[0]['brightness'] = 0
            ret[0]['status'] = 'off'
            ret[0]['imageUrl'] = ''
        redisCli.connection_pool.disconnect()
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getDevDetail', methods=['POST'])
def getDevDetail():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        sql_query = aUtils.getSqlText('device/getDevDetail', {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, {'deviceId': params['json']['deviceId']})
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        redisCli = connect_redis()
        status = redisCli.hget(params['json']['deviceId'], 'status')
        newImage = redisCli.hget(params['json']['deviceId'], 'images')
        realdataStr = redisCli.hget(params['json']['deviceId'], 'realdata')
        if realdataStr and status and newImage:
            realdata = json.loads(realdataStr)
            ret[0]['volt'] = realdata['volt']
            ret[0]['cur'] = realdata['cur']
            ret[0]['curThrd'] = realdata['curThrd']
            ret[0]['light'] = realdata['light']
            ret[0]['temp'] = realdata['temp']
            ret[0]['brightness'] = realdata['brightness']
            ret[0]['status'] = status
            ret[0]['imageUrl'] = json.loads(newImage)['imageUrl']
        else:
            ret[0]['volt'] = 0
            ret[0]['cur'] = 0
            ret[0]['curThrd'] = 0
            ret[0]['light'] = 0
            ret[0]['temp'] = 0
            ret[0]['brightness'] = 0
            ret[0]['status'] = 'off'
            ret[0]['imageUrl'] = ''
        redisCli.connection_pool.disconnect()
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return utils.resData(ret, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/setWorkData', methods=['POST'])
def setWorkData():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        data = {
            'deviceId': params['json']['deviceId'],
            'payload':
                {
                    "method": "d7",
                    "params": {
                        "key": "workVal",
                        "value": {
                            "plan": params['json']['plan']
                        }
                    }
                }
        }
        Mqtt.on_publish(data)
        logging.info(msg)
        return utils.resData(1, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/setCurVal', methods=['POST'])
def setCurVal():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        value = params['json']['cur']
        data = {
            'deviceId': params['json']['deviceId'],
            'payload':
                {
                    "method": "d9",
                    "params": {
                        "value": params['json']['cur']
                    }
                }
        }
        if 500 <= int(value) <= 1500:
            Mqtt.on_publish(data)
            logging.info(msg)
            return utils.resData(1, 'OK')
        else:
            return utils.resData('请输入正确的电流范围：500mA~1500mA', 'ERROR')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getPlanList', methods=['POST'])
def getPlanList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        # data = {
        #     'deviceId': params['json']['deviceId'],
        #     'payload':
        #         {
        #             "method": "d4",
        #             "params": {}
        #         }
        # }
        # Mqtt.on_publish(data)
        # time.sleep(2)
        redisCli = connect_redis()
        planStr = redisCli.hget(params['json']['deviceId'], 'plans')
        ret = []
        if planStr:
            plan = json.loads(planStr)
            ret = plan
        result = {
            'body': ret,
            'status': 'OK'
        }
        redisCli.connection_pool.disconnect()
        msg['res'] = result
        logging.info(msg)
        return result
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/setPlanList', methods=['POST'])
def setPlanList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        path = r'/data/py_data/config/{deviceId}_plan.json'.format(deviceId=params['json']['deviceId'])
        if os.path.exists(path):
            with open(path, 'w+') as f:
                f.write(json.dumps(params['json']['plan']))
        else:
            with open(path, 'x') as f:
                f.write(json.dumps(params['json']['plan']))
        time.sleep(5)
        data = {
            'deviceId': params['json']['deviceId'],
            'payload': {"method": "d7"}
        }
        Mqtt.on_publish(data)
        redisCli = connect_redis()
        redisCli.hset(params['json']['deviceId'], 'plans', json.dumps(params['json']['plan']))
        redisCli.connection_pool.disconnect()
        logging.info(msg)
        return utils.resData(1, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/issueOrder', methods=['POST'])
def issueOrder():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        data = {
            'deviceId': params['json']['deviceId'],
            'payload': {"method": "d0", "params": {'cmd': params['json']['cmd']}}
        }
        Mqtt.on_publish(data)
        logging.info(msg)
        return utils.resData(1, 'OK')
    except Exception as e:
        logging.error(e)
        print(e)
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/operateRoute', methods=['POST'])
def operateRoute():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('routes/' + code, {})
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getRoleList', methods=['POST'])
def getRoleList():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('role/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getGrainListByRoleId', methods=['POST'])
def getGrainListByRoleId():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        code = params['json']['code']
        sql_query = aUtils.getSqlText('role/' + code, {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/getGrainInfoByRoleId', methods=['POST'])
def getGrainInfoByRoleId():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        sql_query = aUtils.getSqlText('role/getGrainInfoByRoleId', {})
        ret = []
        for sql in sql_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        res = utils.resData(ret, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/addRole', methods=['POST'])
def addRole():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        add_sql_query = aUtils.getSqlText('role/addRole', {})
        db.session.execute(add_sql_query, params['json'])
        db.session.commit()
        select_role_query = aUtils.getSqlText('role/getRoleInfoByName', {})
        ret = []
        for sql in select_role_query.split(';'):
            result = db.session.execute(sql, params['json'])
            db.session.commit()
            datas = result.fetchall()
            if datas:
                keys = result.keys()
                for data in datas:
                    result_row = dict(zip(keys, data))
                    ret.append(result_row)
        roleId = ret[0]['roleId']
        add_barn_query = aUtils.getSqlText('role/addBarnByRoleId', {})
        add_grain_query = aUtils.getSqlText('role/addGrainByRoleId', {})
        for barnId in params['json']['barnIds']:
            data = {
                'roleId': roleId,
                'barnId': barnId
            }
            db.session.execute(add_barn_query, data)
            db.session.commit()
        for grainId in params['json']['grainIds']:
            data = {
                'roleId': roleId,
                'grainId': grainId
            }
            db.session.execute(add_grain_query, data)
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/updateRole', methods=['POST'])
def editRoleInfo():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        add_sql_query = aUtils.getSqlText('role/updateRole', {})
        db.session.execute(add_sql_query, params['json'])
        db.session.commit()
        roleId = params['json']['roleId']
        print(roleId)
        delete_barn_grain_query = aUtils.getSqlText('role/deleteInfoByRoleId', {})
        for sql in delete_barn_grain_query.split(';'):
            db.session.execute(sql, {'roleId': roleId})
            db.session.commit()
        add_barn_query = aUtils.getSqlText('role/addBarnByRoleId', {})
        add_grain_query = aUtils.getSqlText('role/addGrainByRoleId', {})
        for barnId in params['json']['barnIds']:
            data = {
                'roleId': roleId,
                'barnId': barnId
            }
            db.session.execute(add_barn_query, data)
            db.session.commit()
        for grainId in params['json']['grainIds']:
            data = {
                'roleId': roleId,
                'grainId': grainId
            }
            db.session.execute(add_grain_query, data)
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


@app.route('/seedlight/deleteRole', methods=['POST'])
def deleteRole():
    try:
        params = utils.getReqParams(request)
        msg = {
            "route": request.url_rule.rule,
            "req-params": params,
            "res": ''
        }
        sql_query = aUtils.getSqlText('role/deleteRole', {})
        for sql in sql_query.split(';'):
            db.session.execute(sql, params['json'])
            db.session.commit()
        res = utils.resData(1, 'OK')
        msg['res'] = res
        logging.info(msg)
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        db.session.rollback()
        return utils.resData(str(e), 'ERROR')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10040, debug=True)
